package cn.paul.wechatshop.controller;

import cn.paul.wechatshop.common.ServerResponse;
import cn.paul.wechatshop.entity.ProductCategory;
import cn.paul.wechatshop.entity.ProductInfo;
import cn.paul.wechatshop.service.IProductCategoryService;
import cn.paul.wechatshop.service.IProductInfoService;
import cn.paul.wechatshop.vo.ProductInfoVo;
import cn.paul.wechatshop.vo.ProductVo;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 徐凌峰
 * @date 2017/12/11 0011
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {


    @Autowired
    private IProductInfoService iProductInfoService;
    @Autowired
    private IProductCategoryService iProductCategoryService;

      @GetMapping("list")
    public ServerResponse productList(){
         //1.查询所有上架商品
          ServerResponse<Page<ProductInfo>> serverResponse = iProductInfoService.findUpAll(null);
          Page<ProductInfo> page = serverResponse.getData();
          List<ProductInfo> productInfoList = Lists.newArrayList();
          for(ProductInfo productInfo :page){
                  productInfoList.add(productInfo);
          }

          //2.查询类目(一次性查出来)
          List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
          //数据库的查询语句应该写在for循环外面,以提高查询速度
          List<ProductCategory> productCategoryList = iProductCategoryService.findByCategoryTypeIn(categoryTypeList);
          List<ProductInfoVo> productInfoVoList = Lists.newArrayList();
          //3.数据封装
          for(ProductCategory productCategory:productCategoryList){
              for(ProductInfo productInfo:productInfoList){
                  if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                      ProductInfoVo productInfoVo=new ProductInfoVo();
                      BeanUtils.copyProperties(productInfo,productInfoVo);
                      productInfoVoList.add(productInfoVo);
                  }
              }
              ProductVo productVo = new ProductVo();
              productVo.setProductInfoVoList(productInfoVoList );
              productVo.setCategoryName(productCategory.getCategoryName());
              productVo.setCategoryType(productCategory.getCategoryType());
          }
          return ServerResponse.createBySuccess(productInfoVoList);
      }
}
